//
//  TRUserDetailViewController.m
//  WeiMiLan
//
//  Created by anan on 14/11/23.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRUserDetailViewController.h"

@interface TRUserDetailViewController ()

@end

@implementation TRUserDetailViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigation];
    
    self.imageViewUserHead.layer.masksToBounds = YES;
    self.imageViewUserHead.layer.cornerRadius = 18; //设置图片圆角的尺度
    
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    self.view.backgroundColor = [UIColor  colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
   
    if ([[userInfo ql_stringForKey:@"HEAD_PIC_URL"] containsString:@"upload/users"]) {
        [self.imageViewUserHead sd_setImageWithURL:[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"urlHeader"]] placeholderImage:[UIImage imageNamed:@"nodata_userheader"]];
    } else {
        [self.imageViewUserHead sd_setImageWithURL:[NSURL URLWithString:[userInfo ql_stringForKey:@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_avator"]];
    }
   
    
    if ((userInfo.count == 0) || [[userInfo ql_stringForKey:@"PHONE"]  isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"PHONE"])
    {
        
        self.textFieldPhoneNum.text = @"";
    } else {
    self.textFieldPhoneNum.text = [NSString stringWithFormat:@"%@",[userInfo ql_stringForKey:@"PHONE"]];
    }
    if ((userInfo.count == 0) || [[userInfo ql_stringForKey:@"WECHAT"] isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"WECHAT"]) {
         self.textFieldWecharNum.text = @"";
    } else {
        self.textFieldWecharNum.text = [NSString stringWithFormat:@"%@",[userInfo ql_stringForKey:@"WECHAT"]];
    }
    
    if ( (userInfo.count == 0) || [[userInfo ql_stringForKey:@"QQ"] isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"QQ"]) {
        self.textFieldQQNum.text = @"";
    } else {
        self.textFieldQQNum.text = [NSString stringWithFormat:@"%@",[userInfo ql_stringForKey:@"QQ"]];
    }

    self.textFieldPhoneNum.enabled = NO;
 
    if ( (userInfo.count == 0) || [[userInfo ql_stringForKey:@"NAME"] isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"NAME"]) {
        self.textFieldNickName.text = @"";
    } else {
        self.textFieldNickName.text = [userInfo ql_stringForKey:@"NAME"];
    }
    if ( (userInfo.count == 0) || [[userInfo ql_stringForKey:@"SIGNATURE"] isEqualToString:@"(null)"] || ![[userInfo allKeys] containsObject:@"SIGNATURE"]) {
        self.textFieldSignature.text = @"";
    } else {
        self.textFieldSignature.text = [NSString stringWithFormat:@"%@",[userInfo ql_stringForKey:@"SIGNATURE"]];
    }
    self.labelId.text = [NSString stringWithFormat:@"微私募ID:%@",userInfo[@"ID"]];
    
    NSString *newPhoneNum = [QLPropertyUtils getStringByKey:@"newPhoneNum" defaultValue:nil];
    if (newPhoneNum&&newPhoneNum.length>0) {
        self.textFieldPhoneNum.text = newPhoneNum;
    }
}

- (void)viewTapped:(UITapGestureRecognizer*)tapGr
{
    [self.textFieldNickName resignFirstResponder];
    [self.textFieldPhoneNum resignFirstResponder];
    [self.textFieldQQNum resignFirstResponder];
    [self.textFieldWecharNum resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"个人资料";
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(exit) forControlEvents:UIControlEventTouchUpInside];
    
    self.weChatNavigationBar.rightButton.hidden = NO;
    [self.weChatNavigationBar.rightButton setImage:nil forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton setTitle:@"保存" forState:UIControlStateNormal];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    [self.weChatNavigationBar.rightButton sizeToFit];
    
}

- (void)showHint:(NSString *)hint {
    if ([hint isEqualToString:@"录音没有开始"]) {
        NSLog(@"dd");
    }
    
    //显示提示信息
    UIView *view = [[UIApplication sharedApplication].delegate window];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.userInteractionEnabled = NO;
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = hint;
    hud.margin = 10.f;
    hud.yOffset = 150.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];
}

- (void)submit
{
    if (self.textFieldNickName.text.length<1) {
        [self showHint:@"请输入昵称"];
        return;
    }
    if (self.textFieldNickName.text.length>32) {
        [self showHint:@"昵称长度不能大于32"];
        return;
    }
    if (self.textFieldPhoneNum.text.length<1) {
        [self showHint:@"请输入手机号码"];
        return;
    }
    if (self.textFieldSignature.text.length<1) {
        [self showHint:@"请输入个性签名"];
        return;
    }
    
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic ql_setObject:self.textFieldPhoneNum.text forKey:@"phone"];
    [dic ql_setObject:self.textFieldQQNum.text forKey:@"qq"];
    [dic ql_setObject:self.textFieldWecharNum.text forKey:@"wechat"];
    [dic ql_setObject:self.textFieldNickName.text forKey:@"name"];
    [dic ql_setObject:self.textFieldSignature.text forKey:@"signature"];
    [dic ql_setInterge:[userInfo ql_intForKey:@"ID"] forKey:@"userId"];
    [QLMaskUtil showMaskLoadingWithView:self.view];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager POST:@"http://ping.vsmu.cn/app/Interface/User?type=9004" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        if ([[dic[@"MESSAGE_INFO"] ql_stringForKey:@"CODE"] isEqualToString:@"0000"]) {
            [[QLUserManager shareInstance] detailWithUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {
                if (data) {
                    [self showHint:@"修改成功"];
                }else{
                    [self showHint:@"修改失败"];
                }
                [QLMaskUtil hideLoadingMaskWithView:self.view];
                [self exit];
            }];
        }else{
            [QLMaskUtil hideLoadingMaskWithView:self.view];
            [self showHint:dic[@"MESSAGE_INFO"][@"MESSAGE"]];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        [self showHint:@"修改失败"];
    }];
}

- (void)exit
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)uploadUserHeadAction:(id)sender
{
    UIActionSheet *choosePhotoActionSheet;
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        choosePhotoActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"选取图片", @"")
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"取消", @"")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:NSLocalizedString(@"相机", @""), NSLocalizedString(@"相册", @""), nil];
    } else {
        choosePhotoActionSheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"选取图片", @"")
                                                             delegate:self
                                                    cancelButtonTitle:NSLocalizedString(@"取消", @"")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:NSLocalizedString(@"相册", @""), nil];
    }
    
    [choosePhotoActionSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSUInteger sourceType = 0;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
            case 0:
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                return;
        }
    } else {
        if (buttonIndex == 1) {
            return;
        } else {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        }
    }
    
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:^{
        
    }];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    self.tmpHeaderImg = [info objectForKey:UIImagePickerControllerEditedImage];
    [self.imageViewUserHead setImage:self.tmpHeaderImg];
    [self uploadImage];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)uploadImage
{
    NSString *userId = [NSStandardUserDefaults objectForKey:@"USER_ID"];
    NSDictionary *parameters = @{@"userId" : userId};

    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [SVProgressHUD show];
    AFHTTPRequestOperation *op = [requestManager POST:@"http://ping.vsmu.cn/app/upload-user-pic" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //do not put image inside parameters dictionary as I did, but append it!
        NSData *data = UIImageJPEGRepresentation(self.tmpHeaderImg,1);
        [formData appendPartWithFileData:data name:@"file.file" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        if ([dic ql_intForKey:@"code"]==0000) {
            [SVProgressHUD showSuccessWithStatus:@"头像上传成功"];
        }
        NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
        NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
        [[QLUserManager shareInstance] detailWithUserId:[userInfo ql_intForKey:@"ID"] callback:^(BOOL isCache, id data) {
            
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"头像上传失败"];
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];
    [op start];
}

- (IBAction)buttonResetPhoneNum:(id)sender
{
    TRVerifyPhoneViewController *vc = [[TRVerifyPhoneViewController alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
    
    [QLPropertyUtils putStringByKey:@"newPhoneNum" value:@""];
}

@end
